#include "stdafx.h"
//-------------------------------------------------------------------------------------------------
//FileNewDlg.cpp : Create New IDF  
//-------------------------------------------------------------------------------------------------
//FreeBSD License
//Copyright 2011 Will Stott All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are
//permitted provided that the following conditions are met:
//
//   1. Redistributions of source code must retain the above copyright notice, this list of
//      conditions and the following disclaimer.
//
//   2. Redistributions in binary form must reproduce the above copyright notice, this list
//      of conditions and the following disclaimer in the documentation and/or other materials
//      provided with the distribution.
//
//THIS SOFTWARE IS PROVIDED BY Will Stott ``AS IS'' AND ANY EXPRESS OR IMPLIED
//WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Will Stott OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
//ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
//ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//The views and conclusions contained in the software and documentation are those of the
//authors and should not be interpreted as representing official policies, either expressed
//or implied, of Will Stott.
//
//----Authors--------------------------------------------------------------------------------------
//created by: will.stott@ucl.ac.uk Nov 2011
//
//----Comments-------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------

#include "ArchiveProcGUI.h"
#include "FileNewHeaderDlg.h"
#include "FileNewDlg.h"
#include "afxdialogex.h"

#include "APDatabase.h"
#include "UraDb.h"
#include "SqlProc.h"




// FileNewDlg dialog

IMPLEMENT_DYNAMIC(FileNewDlg, CDialogEx)

FileNewDlg::FileNewDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(FileNewDlg::IDD, pParent)
	, m_ImageDatasetFile(_T(""))
	, m_DataDir(_T(""))
	, m_ImportImagesDir(_T(""))
	, m_LocalDbConnectionStr(_T(""))
	, m_RemoteDbConnectionStr(_T(""))
	, m_SQLStatementFile(_T(""))
	, m_Results(_T(""))
	, m_ImageSource(IMAGESRC_FILESYS)
	, m_HeaderType(HEADER_STD)
	, m_IDFName(_T(""))
	, m_IDFOwner(_T(""))
	, m_IDFDescription(_T(""))
	, m_IDFVersion(_T(""))
	, m_IDFRepository(_T(""))
{

	
}

FileNewDlg::~FileNewDlg()
{
}

void FileNewDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_IMAGEDATASETFILEEDIT, m_ImageDatasetFile);
	DDV_MaxChars(pDX, m_ImageDatasetFile, 100);
	DDX_Text(pDX, IDC_DATASETDIREDIT, m_DataDir);
	DDV_MaxChars(pDX, m_DataDir, 260);
	DDX_Text(pDX, IDC_FILESYSTEMEDIT, m_ImportImagesDir);
	DDV_MaxChars(pDX, m_ImportImagesDir, 260);
	DDX_Text(pDX, IDC_LOCALDB_CONNECTIONSTR, m_LocalDbConnectionStr);
	DDX_Text(pDX, IDC_REMOTEDB_CONNECTIONSTR, m_RemoteDbConnectionStr);
	DDX_Text(pDX, IDC_SQLSTATEMENTFILEEDIT, m_SQLStatementFile);
	DDV_MaxChars(pDX, m_SQLStatementFile, 260);
	DDX_Text(pDX, IDC_RESULTSEDIT, m_Results);
	DDX_Radio(pDX, IDC_FILESYSRADIO, m_ImageSource);
	DDX_Control(pDX, IDC_DEFINEHEADERBUTTON, m_CustomHeaderButton);
	DDX_Radio(pDX, IDC_STDHEADERRADIO, m_HeaderType);
	DDX_Text(pDX, IDC_IDFNAMEEDIT, m_IDFName);
	DDX_Text(pDX, IDC_IDFOWNEREDIT, m_IDFOwner);
	DDX_Control(pDX, IDC_STDHEADERCOMBO, m_StdHeaderCombo);
	DDX_Text(pDX, IDC_IDFDESCRIPTIONEDIT, m_IDFDescription);
	DDX_Text(pDX, IDC_IDFVERSIONEDIT, m_IDFVersion);
	DDX_Text(pDX, IDC_IDFREPOSITORYEDIT, m_IDFRepository);
	DDX_Control(pDX, IDC_FILESYSTEMBROWSEBUTTON, m_BrowseImageSourceFiles);
	DDX_Control(pDX, IDC_SQLSTATEMENTFILEBROWSEBUTTON, m_SQLStatementFileBrowseCtrl);
	DDX_Control(pDX, IDC_SQLSTATEMENTFILEVIEWBUTTON, m_SQLStatementFileViewCtrl);
	DDX_Control(pDX, IDC_FILESYSTEMEDIT, m_ImageSourceFileCtrl);
	DDX_Control(pDX, IDC_SQLSTATEMENTFILEEDIT, m_SQLStatementFileCtrl);
	DDX_Control(pDX, IDC_LOCALDB_CONNECTIONSTR, m_ImageSourceDbLocalCtrl);
	DDX_Control(pDX, IDC_REMOTEDB_CONNECTIONSTR, m_ImageSourceDbRemoteCtrl);
	DDX_Control(pDX, IDC_TEMPLATEBROWSEBUTTON, m_HeaderCopyFromBrowse);
}


BEGIN_MESSAGE_MAP(FileNewDlg, CDialogEx)
	ON_BN_CLICKED(IDC_DATASETDIRBROWSEBUTTON, &FileNewDlg::OnBnClickedDatasetDirBrowseButton)
	ON_BN_CLICKED(IDC_FILESYSTEMBROWSEBUTTON, &FileNewDlg::OnBnClickedImportFileSystemBrowseButton)
	ON_BN_CLICKED(IDC_SQLSTATEMENTFILEBROWSEBUTTON, &FileNewDlg::OnBnClickedSqlStatementFileBrowseButton)
	ON_BN_CLICKED(IDC_SQLSTATEMENTFILEVIEWBUTTON, &FileNewDlg::OnBnClickedSqlStatementFileViewButton)
	ON_BN_CLICKED(IDOK, &FileNewDlg::OnBnClickedOk)
	ON_BN_CLICKED(IDC_DEFINEHEADERBUTTON, &FileNewDlg::OnBnClickedDefineHeaderButton)
	ON_BN_CLICKED(IDC_IDFVIEWBUTTON, &FileNewDlg::OnBnClickedIdfViewButton)
	ON_BN_CLICKED(IDC_CUSTOMRADIO, &FileNewDlg::OnBnClickedHeaderTypeRadio)
	ON_BN_CLICKED(IDC_STDHEADERRADIO, &FileNewDlg::OnBnClickedHeaderTypeRadio)
	ON_BN_CLICKED(IDC_TEMPLATEHEADERRADIO, &FileNewDlg::OnBnClickedHeaderTypeRadio)
	ON_BN_CLICKED(IDC_TEMPLATEBROWSEBUTTON, &FileNewDlg::OnBnClickedTemplatebrowsebutton)
	ON_BN_CLICKED(IDC_FILESYSRADIO, &FileNewDlg::OnBnClickedImageSourceRadio)
	ON_BN_CLICKED(IDC_LOCALDBRADIO, &FileNewDlg::OnBnClickedImageSourceRadio)
	ON_BN_CLICKED(IDC_REMOTEDBRADIO, &FileNewDlg::OnBnClickedImageSourceRadio)
END_MESSAGE_MAP()


// FileNewDlg message handlers

BOOL FileNewDlg::OnInitDialog()
{
	m_ImageSource = IMAGESRC_FILESYS;
	if ((m_RemoteDbConnectionStr.GetLength() == 0) && (m_ImageSource == IMAGESRC_REMOTE_DB))
		m_ImageSource = IMAGESRC_LOCAL_DB;
	if ((m_LocalDbConnectionStr.GetLength() == 0) && (m_ImageSource == IMAGESRC_LOCAL_DB))
		m_ImageSource = IMAGESRC_REMOTE_DB;

	CDialogEx::OnInitDialog();

	m_StdHeaderCombo.SetCurSel(0);
	OnBnClickedHeaderTypeRadio();
	OnBnClickedImageSourceRadio();

	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}


void FileNewDlg::OnBnClickedOk()
{
	UpdateData(TRUE);

	ClearOutputResultMsg();

	if ( m_ImageDatasetFile.GetLength() <= 0 )
		CArchiveProcGUIApp::UserErrorMsg("User Error"," No name given for the new Image Dataset File (IDF) file", "success", "enter a name and try again", MB_OK | MB_ICONSTOP );	
	else
	{
		CString  IDFfile(GetIDFPathFilename());
		
		HANDLE hIDFNew = CreateFile(IDFfile, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
		if (hIDFNew == INVALID_HANDLE_VALUE)
			CArchiveProcGUIApp::UserErrorMsg("User Error"," IDF file cannot be created, it may already exist", "success", "select another file and (or) directory, then try again", MB_OK | MB_ICONSTOP );	
		else
		{
			CloseHandle(hIDFNew);

			if(DeleteFile(IDFfile) == FALSE)
				CArchiveProcGUIApp::UserErrorMsg("System Error"," Unable to delete the temporary IDF file", "success", "please report his problem", MB_OK | MB_ICONSTOP );	
			else
			{
				ImageDataset idf(GetIDFPathFilename(), "Image workflow engine v0.0 - image dataset file", "Doc");

				idf.SetHeaderValue(ImageDataset::xmlHeaderOwner, CStringA(m_IDFOwner));
				idf.SetHeaderValue(ImageDataset::xmlHeaderName, CStringA( m_IDFName));
				idf.SetHeaderValue(ImageDataset::xmlHeaderDescription, CStringA(m_IDFDescription));
				idf.SetHeaderValue(ImageDataset::xmlHeaderRepository, CStringA(m_IDFRepository));
				idf.SetHeaderValue(ImageDataset::xmlHeaderVersion, CStringA(m_IDFVersion));
				idf.SetHeaderValue(ImageDataset::xmlHeaderRuntimeDir, CStringA(m_DataDir));

				if ( m_ImageSource != IMAGESRC_FILESYS)
					idf.SetHeaderValue(ImageDataset::xmlHeaderDataQueryFile, CStringA(m_SQLStatementFile));

				bool ok = false;
				if ( m_ImageSource == IMAGESRC_FILESYS )
					ok = CreateImageDataSetFromFileSystem(idf);
				else
					ok = CreateImageDataSetFromDb(idf);

				if (ok == true)
				{
					if (idf.SaveFile(NULL) == false)
						CArchiveProcGUIApp::UserErrorMsg("System Error","Failed to save IDF file", "success", "please report his problem", MB_OK | MB_ICONSTOP );	
					else
						CDialogEx::OnOK();
				}
 			}
		}
	}
}

void FileNewDlg::OnBnClickedImageSourceRadio()
{
	UpdateData(TRUE);

	if ( m_ImageSource == IMAGESRC_FILESYS)
	{
		m_BrowseImageSourceFiles.EnableWindow(TRUE);
		m_ImageSourceFileCtrl.EnableWindow(TRUE);
		m_SQLStatementFileBrowseCtrl.EnableWindow(FALSE);
		m_SQLStatementFileViewCtrl.EnableWindow(FALSE);
		m_SQLStatementFileCtrl.EnableWindow(FALSE);
		m_ImageSourceDbLocalCtrl.EnableWindow(FALSE);
		m_ImageSourceDbRemoteCtrl.EnableWindow(FALSE);
	}
	else if ( m_ImageSource == IMAGESRC_LOCAL_DB)
	{
		m_BrowseImageSourceFiles.EnableWindow(FALSE);
		m_ImageSourceFileCtrl.EnableWindow(FALSE);
		m_SQLStatementFileBrowseCtrl.EnableWindow(TRUE);
		m_SQLStatementFileViewCtrl.EnableWindow(TRUE);
		m_SQLStatementFileCtrl.EnableWindow(TRUE);
		m_ImageSourceDbLocalCtrl.EnableWindow(TRUE);
		m_ImageSourceDbRemoteCtrl.EnableWindow(FALSE);
	}
	else
	{
		m_BrowseImageSourceFiles.EnableWindow(FALSE);
		m_ImageSourceFileCtrl.EnableWindow(FALSE);
		m_SQLStatementFileBrowseCtrl.EnableWindow(TRUE);
		m_SQLStatementFileViewCtrl.EnableWindow(TRUE);
		m_SQLStatementFileCtrl.EnableWindow(TRUE);
		m_ImageSourceDbRemoteCtrl.EnableWindow(TRUE);
		m_ImageSourceDbLocalCtrl.EnableWindow(FALSE);
	}
}


void FileNewDlg::OnBnClickedTemplatebrowsebutton()
{
	CArchiveProcGUIApp::UserMsg("Not yet implemented", "Wait for next release!", MB_OK | MB_ICONSTOP );
}

void FileNewDlg::OnBnClickedHeaderTypeRadio()
{
	UpdateData(TRUE);

	m_CustomHeaderButton.EnableWindow( (m_HeaderType == HEADER_CUSTOM) ? TRUE : FALSE );
	m_HeaderCopyFromBrowse.EnableWindow( (m_HeaderType == HEADER_COPYFROM) ? TRUE : FALSE );

}

void FileNewDlg::OnBnClickedDefineHeaderButton()
{
	UpdateData(TRUE);

	FileNewHeaderDlg dlg;

	dlg.DoModal();
}


void FileNewDlg::OnBnClickedImportFileSystemBrowseButton()
{
	UpdateData(TRUE);

	CString datasetDir(m_ImportImagesDir);
	CWinAppEx *pApp = dynamic_cast<CWinAppEx *>(AfxGetApp());
	if (pApp)
	{
		if (pApp->GetShellManager()->BrowseForFolder(datasetDir, this, datasetDir, L"Select directory containing images", BIF_NEWDIALOGSTYLE | BIF_RETURNONLYFSDIRS) )
			m_ImportImagesDir = datasetDir;
	}

	UpdateData(FALSE);
}

void FileNewDlg::OnBnClickedDatasetDirBrowseButton()
{
	UpdateData(TRUE);

	CString datasetDir(m_DataDir);
	CWinAppEx *pApp = dynamic_cast<CWinAppEx *>(AfxGetApp());
	if (pApp)
	{
		if (pApp->GetShellManager()->BrowseForFolder(datasetDir, this, datasetDir, L"Select directory for dataset", BIF_NEWDIALOGSTYLE | BIF_RETURNONLYFSDIRS) )
			m_DataDir = datasetDir;
	}

	UpdateData(FALSE);
}


void FileNewDlg::OnBnClickedSqlStatementFileBrowseButton()
{
	UpdateData(TRUE);

	CFileDialog dlgFile(TRUE);

	CString SqlFile( m_SQLStatementFile);

	const int c_cMaxFiles = 100;
	const int c_cbBuffSize = (c_cMaxFiles * (MAX_PATH + 1)) + 1;
	dlgFile.GetOFN().lpstrFile = SqlFile.GetBuffer(c_cbBuffSize);
	dlgFile.GetOFN().nMaxFile = c_cbBuffSize;
	dlgFile.GetOFN().lpstrFilter = L"Text Files\0*.txt;All Files\0*.*\0\0";
	dlgFile.GetOFN().Flags = dlgFile.GetOFN().Flags | OFN_FILEMUSTEXIST;

	if ( dlgFile.DoModal() == IDOK )
	{
		m_SQLStatementFile = SqlFile;
	}

	SqlFile.ReleaseBuffer();

	UpdateData(FALSE);
}


void FileNewDlg::OnBnClickedSqlStatementFileViewButton()
{
	//check files exists
	UpdateData(TRUE);

	HANDLE FileExists = CreateFile(m_SQLStatementFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
	if (FileExists == INVALID_HANDLE_VALUE)
		CArchiveProcGUIApp::UserErrorMsg("User Error", "SQL Statement file does not exist", "success", "select another file and try again", MB_OK | MB_ICONSTOP );	
	else
	{
		CloseHandle(FileExists);
		ShellExecute(NULL, L"edit", m_SQLStatementFile, NULL, NULL, SW_SHOWNORMAL);
	}
}

void FileNewDlg::OnBnClickedIdfViewButton()
{
	UpdateData(TRUE);

	CString idfFile(GetIDFPathFilename());

	HANDLE FileExists = CreateFile(idfFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
	if (FileExists == INVALID_HANDLE_VALUE)
		CArchiveProcGUIApp::UserErrorMsg("User Error", "IDF file does not exist", "success", "select another file and try again", MB_OK | MB_ICONSTOP );	
	else
	{
		CloseHandle(FileExists);
		ShellExecute(NULL, L"edit", idfFile, NULL, NULL, SW_SHOWNORMAL);
	}
}

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//		private functions
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

bool FileNewDlg::CreateImageDataSetFromFileSystem(ImageDataset &idf)
{
	bool rc = false;

	OutputResultMsg( "Creating dataset from file system" );

	WIN32_FIND_DATA FindFileData; 
	HANDLE hFind; 

	CString importFolder(m_ImportImagesDir);
	if (importFolder[m_ImportImagesDir.GetLength()-1] != '\\')
		importFolder += "\\";
	CString importFileSpec(importFolder);
	importFileSpec += "*.bmp";

	int imagecnt = 0;
	hFind = FindFirstFile(importFileSpec, &FindFileData); 
	if (hFind == INVALID_HANDLE_VALUE)
	{
		CArchiveProcGUIApp::UserErrorMsg("User Error","No image BMP files found in directory", "success", "select another directory and try again", MB_OK | MB_ICONSTOP );	
		OutputResultMsg( "No image BMP files found in directory",  CStringA(importFileSpec));
	}
	else
	{
		rc = true;
		do
		{
			CString processingBMP(FindFileData.cFileName);
	
			if (idf.AddImage(processingBMP.Mid(0, processingBMP.GetLength() - 4)) == false)
			{
				CArchiveProcGUIApp::UserErrorMsg("System Error","Failed to add image to IDF", "success", "report this problem", MB_OK | MB_ICONSTOP );	
				OutputResultMsg( "No image BMP files found in directory",   CStringA(processingBMP));
				rc = false;
			}
			else
			{
				CString srcDicom(importFolder);
				srcDicom += processingBMP;
				CString destDicom(GetDataDir());
				destDicom += "\\";
				destDicom += processingBMP;

				if (CopyFile(srcDicom, destDicom, FALSE) == false)
				{
					CArchiveProcGUIApp::UserErrorMsg("System Error","Failed to copy file to IDF directory", "success", "delete files and retry", MB_OK | MB_ICONSTOP );	
					OutputResultMsg( "file could not be copied",  CStringA(processingBMP));
					rc = false;
				}
				else
				{
					CStringA status;
					status.Format("%d: BMP file saved ok", imagecnt);
					OutputResultMsg(status, CStringA (processingBMP));
				}
			}
		}
		while(FindNextFile(hFind, &FindFileData) != 0);

		if ( rc == true)
		{
			DWORD dwError = GetLastError();
			if (dwError != ERROR_NO_MORE_FILES) 
			{
				CArchiveProcGUIApp::UserErrorMsg("System Error","Failed to process all files in directory", "success", "report this problem", MB_OK | MB_ICONSTOP );	
				CStringA status;
				status.Format("%d: problem %d opening file", dwError);
				OutputResultMsg( "Failed to process all files in directory",  status);
				rc = false;
			}
		}
		FindClose(hFind);
	}

	if ( rc == true)
		OutputResultMsg( "Dataset successfully created from file system" );
	else
		OutputResultMsg( "Dataset not created from file system successfully" );

	return rc;
}

bool FileNewDlg::CreateImageDataSetFromDb(ImageDataset &idf)
{
	bool rc = false;

	OutputResultMsg( "Creating dataset from database" );

	HANDLE hSQLStatementExists = CreateFile(m_SQLStatementFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
	if (hSQLStatementExists == INVALID_HANDLE_VALUE)
		CArchiveProcGUIApp::UserErrorMsg("User Error"," SQL Statement file does not exist", "success", "select another SQL statement file and try again", MB_OK | MB_ICONSTOP );	
	else
	{
		CloseHandle(hSQLStatementExists);

		CString DbConnectionLabel;
		DbConnectionLabel = (m_ImageSource == IMAGESRC_REMOTE_DB) ?  m_RemoteDbConnectionStr : m_LocalDbConnectionStr;
		
		UraDb conn;
		if (conn.OpenSession(DbConnectionLabel.AllocSysString()) == false)
			CArchiveProcGUIApp::UserErrorMsg("System Error","Open database failed", "success", "check database connection", MB_OK | MB_ICONSTOP );
		else
		{
			OutputResultMsg( "open database session ok" );

			SqlProc sql;
			sql.OpenStatementsFile(m_SQLStatementFile);

			rc = true;

			int imagecnt = 0;
			for (std::vector<std::wstring *>::iterator statement = sql._Statements.begin(); statement != sql._Statements.end(); ++statement ) 
			{
				LPCOLESTR SqlQuery = (*statement)->c_str();   
			
				if ( ! conn.GetRecords(SqlQuery, 100))
				{
					CArchiveProcGUIApp::UserErrorMsg("System Error","Read database failed", "success", "check database connection", MB_OK | MB_ICONSTOP );
					if (FAILED(conn.GetErrorCode()))
					{
						CStringA errMsg(conn.GetErrorMsg()); 
						OutputResultMsg("conn.GetRecords failed, msg: ", errMsg);
					}
					else
						OutputResultMsg("conn.GetRecords failed, msg: ", "(no HRESULT message)");
					rc = false;
				}
				else
				{
					if ( conn._Images.size() == 0 )
					{
						CArchiveProcGUIApp::UserErrorMsg("System Error","Database returned no records", "success", "report this problem", MB_OK | MB_ICONSTOP );
						USES_CONVERSION;
						CStringA errMsg(OLE2CT(SqlQuery));
						OutputResultMsg("conn.GetRecords returned no records for:  ", errMsg );
						rc = false;
					}

					ImageData *pImageData;
					for (std::vector<ImageData *>::iterator iter = conn._Images.begin(); iter != conn._Images.end(); ++iter ) 
					{
						pImageData = *iter;
						if (pImageData->GetErrorCode() != ImageData::NoError )
						{
							if (pImageData->GetErrorCode() == ImageData::DicomError )
								OutputResultMsg("Dicom Error ", CStringA(pImageData->GetDicomFile()->GetErrorMsg()));
							else
								OutputResultMsg("ImageData Error ", CStringA(pImageData->GetErrorMsg()) );
							rc = false;
						}
						else
						{
							CStringA processingDicom (pImageData->GetDicomFile()->GetDicomRef());

							std::wstring DataDir = GetDataDirBackslash(); 
							if ( pImageData->GetBitMap()->SaveAsFile(DataDir) == false)
							{
								CArchiveProcGUIApp::UserErrorMsg("System Error","Failed to save file", "success", "check you have access to the IDF directory", MB_OK | MB_ICONSTOP );
								OutputResultMsg("BMP file save error", processingDicom);
								rc = false;
							}
							else
							{
								if ( idf.AddImage(pImageData->GetDicomFile()->GetDicomRef()) == false)
								{
									CArchiveProcGUIApp::UserErrorMsg("System Error","Failed to add image to IDF", "success", "report this problem", MB_OK | MB_ICONSTOP );
									OutputResultMsg("Failed to add image to IDF", processingDicom);
									rc = false;
								}
								else
								{
									CStringA status;
									status.Format("%d: BMP file saved ok", imagecnt);
									OutputResultMsg(status, processingDicom);
									imagecnt++;
								}
							}
						}
					}
				}
				if ( rc == false)
					break;
			}
			conn.CloseDbSession();
			OutputResultMsg("close database session ok");
		}
	}

	if ( rc == true)
		OutputResultMsg( "Dataset successfully created from database" );
	else
		OutputResultMsg( "Dataset not created from database successfully" );

	return rc;
}

CString FileNewDlg::GetIDFPathFilename()
{
	CString  IDFfile(GetDataDir());

	int nameLen = m_ImageDatasetFile.Find(_T('.'));
	if (nameLen > 0 )
		m_ImageDatasetFile.Delete(nameLen, m_ImageDatasetFile.GetLength());
	m_ImageDatasetFile += ".idf";

	IDFfile += '\\' + m_ImageDatasetFile;

	return IDFfile;
}



CString FileNewDlg::GetDataDir()
{
	CString  folder(m_DataDir);

	if (folder[m_DataDir.GetLength()-1] == '\\')
		folder.Delete(m_DataDir.GetLength()-1, m_DataDir.GetLength());

	return folder;
}

CString FileNewDlg::GetDataDirBackslash()
{
	CString folder(GetDataDir());
	folder += "\\";
	return folder;
}

void	FileNewDlg::OutputResultMsg(LPCSTR msg1, LPCSTR msg2)
{
	m_Results += msg1;
	if (msg2 != NULL)
	{
		m_Results += ": "; 
		m_Results += msg2;
	}
	m_Results += "\r\n";

	UpdateData(FALSE);
	::Sleep(100);
}

void	FileNewDlg::ClearOutputResultMsg()
{
	m_Results.Empty();
	UpdateData(FALSE);
}

//-------------------------------------------------------------------------------------------------
//			E N D   O F   F I L E
//-------------------------------------------------------------------------------------------------





















